# -*- coding: utf-8 -*-
from facepp import API, File
from PIL import Image
import os
import time
import logging
import sys

reload(sys)
sys.setdefaultencoding('utf8')

class facePic:
    paths = []
    input_path = ''
    handle_path = './handle'
    output_path = './output'

    def __init__(self, input_path):
        self.input_path = input_path

    def getPic(self, i_path):
        if os.path.isdir(self.input_path + '/' + i_path):
            p_Dir =  os.listdir(self.input_path + '/' + i_path)
            for item in p_Dir:
                self.getPic(i_path + '/' + item)
        else:
            self.paths.append(i_path)

    def resizePic(self, input_dir, output_dir, file_name, input_width):
        im = Image.open(input_dir + '/' + file_name)
        width, height = im.size
        pic_format = im.format
        if width < input_width:
            resize_w = width
        else:
            resize_w = input_width
        resize_h = resize_w * height / width
        resizedIm = im.resize((resize_w, resize_h))
        self.createDir(output_dir + '/' + file_name)
        resizedIm.save(output_dir + '/' + file_name, pic_format)
    
    def handlePic(self, api, file_name):
        success = False
        res = False
        while not success:
            try:
                res = api.detect(image_file=File(self.handle_path + '/' + file_name))
            except Exception, e:
                print e
                time.sleep(1)
                continue
            success = True
        print res
        if not res['faces']:
            logging.warning(file_name + ' detect failed')  
            return False
        face_info = res['faces'][0]['face_rectangle']
        #开始截取
        im=Image.open(self.handle_path + '/' + file_name)
        pic_format = im.format
        pic_size = im.size
        head_width = face_info['width']
        head_height = face_info['height']

        y0 = face_info['top'] - head_height
        y1 = face_info['top'] + head_height * 2.5
        if y0 < 0:
            y0 = 0
            y1 = y1 - y0
        if y1 > pic_size[1]:
            y1 = pic_size[1]
            if (y0 - (y1 - pic_size[1])) > 0:
                y0 = y0 - (y1 - pic_size[1])
            else:
                y0 = 0
        height = y1 - y0
        width = height / 7 * 5
        
        #判断头部的位置来计算要截取的范围
        head_left = face_info['left']
        x0 = head_left - (width - head_width) / 2
        x1 = face_info['left'] + head_width + (width - head_width) / 2

        #进行位置补偿
        if x0 < 0:
            x0 = 0
            x1 = x1 - x0
        if x1 > pic_size[0]:
            x1 = pic_size[0]
            if x0 - (x1 - pic_size[0]) > 0:
                x0 = x0 - (x1 - pic_size[0])
            else:
                x0 = 0
        box = (x0, y0, x1, y1)
        crop = im.crop(box)
        self.createDir(self.output_path + '/' + file_name)
        crop.save(self.output_path + '/' + file_name, pic_format) 

        #重新缩放
        self.resizePic(self.output_path, self.output_path, file_name, 500)
        return True

    def createDir(self, file_name):
        file_name_array = os.path.split(file_name)
        isExists=os.path.exists(file_name_array[0])
        if not isExists:
            os.makedirs(file_name_array[0]) 


if __name__ == "__main__":
    input_path = './source'
    API_KEY = "GPapGXFqOuVCB13T5lPnkaZcsk8zsGy4"
    API_SECRET = "eoQ2ev_SmWxN4jbaYNOx0YsBAnR21ouk"
    logging.basicConfig(level=logging.WARNING, filename='./log.txt', filemode='w')  
    pathDir =  os.listdir(input_path)
    api = API(API_KEY, API_SECRET)
    fp = facePic(input_path)
    for sub in pathDir:
        fp.getPic(sub)
    for pic in fp.paths:
        fp.resizePic(fp.input_path, fp.handle_path, pic, 2000)
        fp.handlePic(api, pic)
        time.sleep(1)